package SparkExercises.kejian4;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class LianXi2 {
    public static void main(String[] args) {
        /**
         * 已知一个普通的文本文件words.txt，
         * 里面每一行都是英文语句，请写一个spark程序，
         * 统计每个单词的出现次数（按空格分割，每一个子字符串看成一个单词），并输出到控制台。
         */
        SparkConf sparkConf = new SparkConf().setAppName("LianXi2").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
        JavaRDD<String> rdd = sc.textFile("./data/words.txt").flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String s) throws Exception {
                String[] s1=s.split(" ");
                return Arrays.asList(s1).iterator();
            }
        });
        JavaPairRDD<String, Integer> pairRDD = rdd.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<>(s,1);
            }
        });
        JavaPairRDD<String, Iterable<Integer>> g =pairRDD.groupByKey();

        JavaRDD<Tuple2<String,Integer>> map =g.map(new Function<Tuple2<String, Iterable<Integer>>, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> call(Tuple2<String, Iterable<Integer>> v1) throws Exception {
                String key =v1._1;
                Integer val =0;
                for (Integer a : v1._2){
                    val += a;
                }
                return new Tuple2<>(key,val);
            }
        });
        System.out.println(map.collect());
    }
}
